package tkaczyk.simtalk.message;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MessagePreparer {
	private int seqNo = 0;
	private String nick = "Unknown";
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public MessagePreparer() {
	}

	public Message newMessage(String body) {
		Message msg = new Message();
		msg.body = body;
		msg.nick = nick;
		msg.sent = new Date();
		msg.seqNo = seqNo++;
		msg.target = Message.Target.OUTGOING;
		msg.xml = createXMLString(msg);
		return msg;
	}

	public static String createXMLString(Message msg) {
		StringBuilder xml = new StringBuilder();
		xml.append("<message seqNo=\"" + msg.seqNo + "\">\n");
		xml.append("  <nick><![CDATA[" + msg.nick.replaceAll("]]>", "]]]]><![CDATA[>") + "]]></nick>\n");
		xml.append("  <sent>" + dateFormat.format(msg.sent) + "</sent>\n");
		xml.append("  <body><![CDATA[" + msg.body.replaceAll("]]>", "]]]]><![CDATA[>") + "]]></body>\n");
		xml.append("</message>\n");
		return xml.toString();
	}
	
	public void setNick(String nick) {
		this.nick = nick;
	}
	
	public void resetSeqNo() {
		seqNo = 0;
	}
}
